<template>
  <div
    class="home-dictionary"
    ref="dictionary"
    oncontextmenu="window.event.returnValue=false"
  >
    <el-tree
      :data="modelFileList"
      highlight-current
      :props="defaultProps"
      :expand-on-click-node="false"
      @node-click="debounceHandleItem"
      node-key="nodeId"
      :default-expanded-keys="defaultKeys"
      @node-contextmenu="handleRightItem"
      @node-expand="nodeExpand"
      @node-collapse="nodeCollapse"
    >

      <span
        class="custom-tree-node"
        slot-scope="{ node, data }"
      >
        <span>
          <i :class="data.checkIcon"></i>
          {{ node.label }}
        </span>
      </span>

    </el-tree>

    <!-- 右键 -->
    <rightClickMenuDialog
      v-if="isRightClickMenu"
      @addMenuChild="debounceAddMenuChild"
      @init="_getInitTree"
    ></rightClickMenuDialog>

  </div>
</template>

<script>
import rightClickMenuDialog from "./rightClickMenuDialog/index";
const modelFileList = [];
import rightMenuMixin from "./rightMenuMixin";
// import { item1, item2, item3, item4 } from "./formConfig";
export default {
  name: "homeDictionary",
  data() {
    return {
      modelFileList,
      defaultProps: {
        children: "children",
        label: "nodeName",
      },
      menuLeft: 0,
      menuTop: 0,
      modelName: "",
      defaultKeys: [],
      selectItem: {},
      debounceHandleItem: null,
      debounceAddMenuChild: null,
    };
  },
  components: {
    rightClickMenuDialog,
  },
  mixins: [rightMenuMixin],

  created() {
    if (this.$route.query && this.$route.query.name) {
      this._getInitTree();
    }
    // 防抖
    this.debounceHandleItem = this.debounceFun(this.handleItem, 500);
    this.debounceAddMenuChild = this.debounceFun(this.addMenuChild, 500);
  },
  mounted() {
    document.body.onclick = () => {
      this.isRightClickMenu = false;
    };
    this.$bus.$on("updateTree", () => {
      this._getInitTreeItem();
    });
  },
  methods: {
    // 初始化
    init($data) {
      console.log($data);
      let { id, name } = { ...$data };
      let data = {
        nodeName: id.split("#")[0],
        nodeId: id,
        checkIcon: "el-icon-s-cooperation",
      };
      this.modelName = name;
      this.modelFileList.push(data);
    },
    // 节点展开触发的事件
    nodeExpand(data) {
      let index = this.defaultKeys.findIndex((nodeId) => {
        return nodeId == data.nodeId;
      });
      if (index == -1) {
        this.defaultKeys.push(data.nodeId);
      }
    },
    // 节点关闭触发的事件
    nodeCollapse(data) {
      this.defaultKeys.some((item, i) => {
        if (item === data.nodeId) {
          // 删除关闭节点
          this.defaultKeys.length = i;
        }
      });
    },
    // 获取树
    async _getInitTree() {
      this.modelName = this.$route.query.name;
      let res = await this.$http.get(
        "/dictionary/tree?modelName=" + this.modelName
      );
      if (res.code == 200) {
        this.modelFileList = [res.data];
        let index = this.defaultKeys.findIndex((nodeId) => {
          return nodeId == res.data.nodeId;
        });
        if (index == -1) {
          this.defaultKeys.push(res.data.nodeId);
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    // 局部更新树
    async _getInitTreeItem() {
      this.modelName = this.$route.query.name;
      let res = await this.$http.get(
        `/dictionary/tree?modelName=${this.modelName}&nodeId=${this.selectItem.nodeId}`
      );
      if (res.code == 200) {
        let data = res.data;
        this.selectItem.nodeName = data.nodeName;
        this.selectItem.children = [];
        this.selectItem.children.push(...data.children);
      }
    },
    // 点击某一项
    async handleItem(item) {
      this.selectItem = item;
      item.nodeId = item.nodeId.replace(/#/g, "%23");
      let res = await this.$http.get(
        `/dictionary/dynamicForm?modelName=${this.modelName}&nodeId=${item.nodeId}`
      );
      let obj = { title: this.modelName, item: res.data, id: item.nodeId };
      this.$store.commit("setPageFormConfig", obj);
      setTimeout(() => {
        this.isRightClickMenu = false;
      });
      console.log(this.$$store);
    },
    // 右键点击
    handleRightItem(e, item) {
      this.isRightClickMenu = false;
      let positonInfo = {
        x: e.clientX + 23,
        y: e.clientY,
      };
      this.$store.commit("setRightMenuPosition", positonInfo);
      this.selectMenuTtem = item;
      // 设置右键菜单的子菜单
      console.log("子菜单");
      console.log(item);
      this.setMenuRight(item);
      setTimeout(() => {
        this.isRightClickMenu = true;
      }, 1);
    },
    // 设置菜单
    async setMenuRight(item) {
      console.log("菜单");
      let del = {
        modelName: this.modelName,
        nodeId: item.nodeId.replace(/#/g, "%23"),
        reference: item.reference,
      };
      if (this.rightMenuData[item.nodeId]) {
        this.$store.commit(
          "setRightMenuChild",
          this.rightMenuData[item.nodeId]
        );
        return false;
      }
      let child = {
        childDescriptors: [],
        siblingDescriptors: [],
        del,
        isChild: true,
        isSibling: true,
      };
      this.$store.commit("setRightMenuChild", child);
      let res = await this.$http.get(
        `/dictionary/descriptors?modelName=${
          this.modelName
        }&parentId=${item.nodeId.replace(/#/g, "%23")}`
      );
      // 设置菜单
      let menu = {
        childDescriptors: this._handleMenu(item, res.data.childDescriptors),
        siblingDescriptors: this._handleMenu(item, res.data.siblingDescriptors),
        isChild: res.data.childDescriptors.length > 0 ? true : false,
        isSibling: res.data.siblingDescriptors.length > 0 ? true : false,
        del,
      };

      let data = {
        id: item.nodeId,
        data: menu,
      };
      // 设置右键菜单
      this.$store.commit("setRightMenuChild", menu);
      // 保存菜单
      this.rightMenuData = data;
    },
    // 处理菜单
    _handleMenu(item, menu) {
      let $menu = [];
      menu.forEach(($item) => {
        let param = {
          modelName: this.modelName,
          nodeType: $item.value,
          parentId: item.nodeId,
          reference: $item.reference,
        };
        $menu.push({
          name: $item.value,
          method: "addMenuChild",
          isShow: true,
          param,
        });
      });
      return $menu;
    },
    // 添加子菜单
    async addMenuChild(data) {
      let res = await this.$http.post("/dictionary/addNode", data);
      if (res.code == 200) {
        this.isRightClickMenu = false;
        this._getInitTree();
      }
    },
  },
};
</script>

<style lang="scss">
.home-dictionary {
  width: 300px;
  margin: 20px;
  .el-tree {
    font-size: 14px;
  }
  .pull-right {
    float: right;
  }
  li {
    list-style: none;
  }
}
</style>